<template lang="pug">
  .clearfix
    .form-shebao-title.font-16.font-weight 附件
    .clearfix.bg-white.pall-20
      .text-gray-9.pl-110.pb-20(v-if="!isOnlyView") 仅支持上传10M以内的doc、xlsx、zip文件
      Form.ivu-row(ref="formEnclosure" :model="formEnclosure" :rules="rules" :label-width="100")
        FormItem.form-item.ivu-col(v-for="item, index of formEnclosureItem" :label="item.label + '：'" :key="index" :class="item.style" :prop="item.prop" v-if="item.isShow")
          Row
            Col.pl-10(span="3" v-if="!isOnlyView")
              //- :isCanUpload="item.files.length > 0 ? false : true"
              UploadZip(v-if="item.uploadType === 'zip'" @before="handleBeforeUpload" @uploadZip="handleUploadSuccessZip" :companyId="companyId" :employeeId="employeeId" :params="params" :row="index" :isCanUpload="item.files.length > 0 ? false : true")
              Upload(v-else @before="handleBeforeUpload" @upload="handleUploadSuccess" :employeeId="employeeId" :params="params" :row="index" :isCanUpload="true")
              Input.display-none(v-model="formEnclosure[item.model]" :placeholder="item.placeholder")
            Col(span="21")
              //- Tag(v-for="c_item, c_index in item.files" :name="c_item.name" :closable="!isOnlyView" @on-close="deleteEmpAtta(index, c_index, c_item.id)" @on-change="handlechangeTag(index, c_index, c_item.id)") {{c_item.name}}
              .download-btn.display-inline-block.mr-10.relative(v-for="c_item, c_index in item.files")
                //- Button(:to="c_item.downLoadUrl" target="_blank" :class="!isOnlyView ? 'pr-30' : ''" icon="ios-cloud-download-outline" size="small") {{c_item.name}} - {{c_item.downLoadUrl}}
                Button.btn-follow-txt(v-if="item.prop === 'yuangongzhaopian'" target="_blank" :class="!isOnlyView ? 'pr-55' : 'pr-30'" size="small") {{c_item.name}}
                Button(v-else-if="c_item.houzhui === 'jpg' || c_item.houzhui === 'png' || c_item.houzhui === 'gif'" :class="!isOnlyView ? 'pr-55' : 'pr-30'" size="small" @click="previewImg(c_item.downLoadUrl)") {{c_item.name}}
                Button.btn-follow-txt(v-else :class="!isOnlyView ? 'pr-55' : 'pr-30'" size="small") {{c_item.name}}
                //- 下载
                //- p.text-error(v-if="item.prop === 'yuangongzhaopian'") 员工照片 {{c_item.isIdCard}}
                //- p.text-info(v-if="item.prop === 'fujian'") 附件
                Icon.btn-r-download(v-if="item.prop === 'yuangongzhaopian'" type="md-download" @click="c_item.isIdCard?downLoad(c_item.downLoadUrl,c_item.name):batchPictureUpload()" :class="!isOnlyView ? 'r-25' : 'r-5'")
                Icon.btn-r-download(v-else type="md-download" @click="accessoryDownload(c_item.downLoadUrl)" :class="!isOnlyView ? 'r-25' : 'r-5'")
                //- Button.btn-r-download(type="text" icon="ios-cloud-download-outline" :to="c_item.downLoadUrl" target="_blank")
                //- Icon.btn-r-close(v-if="!isOnlyView" type="md-close" @click="deleteEmpAtta(index, c_index, c_item.id)")
                //- 删除
                Poptip(
                  v-if="!isOnlyView&&!item.isIdCard"
                  confirm
                  title="是否删除该附件"
                  @on-ok="listenCall(item.fn, index, c_index, c_item.associationId)"
                  width="200"
                )
                  Icon.btn-r-close(type="md-close")
          p.text-gray-9.pt-10.pb-10.pl-10(v-if="item.prop === 'yuangongzhaopian' && !isOnlyView") 标准文件格式：员工照片放入一个文件夹，文件夹以身份证号码命名，选择文件并压缩成zip/rar文件

    //- 仅展示详情时的按钮
    .clearfix.text-center.mt-20.mb-20(v-if="isOnlyView")
      Button.mr-10(type="info" @click="handlepageUp") 查看上一页
      Button.mr-10(v-if="hasEdit && !isFromWaitInduction" type="info" @click="handleModify") 修改
      Button.mr-10(type="info" @click="handlepageDown") 查看下一页
      //- Button(type="info" ghost @click="goEmployeeBookList()") 返回花名册
      Button(v-if="!isFromRoster" type="info" ghost @click="goEmployeeBookList()") 返回花名册
      Button(v-if="isFromRoster" type="info" ghost @click="goRoster()") 返回员工管理

    //- 新建或修改时的按钮
    .clearfix.text-center.mt-20.mb-20(v-if="!isOnlyView")
      Button.mr-10(type="info" @click="handlepageUp") 上一步
      //- Button.mr-10(type="info" ) 保存
      //- Button(type="info" @click="handleSubmit('formEnclosure')" :disabled="!employeeId") 下一步
      Button(type="info" @click="handleSubmit('formEnclosure')") 下一步

    //-图片预览
    Modal(title="附件预览" v-model="isPreviewImgModal" footer-hide)
      img(:src="currentPreviewImg")
</template>

<script>
import { EmployeesApi } from '@/api/Employees.api.js'
import { Common } from '@/utils/common.js'
import Upload from '@/components/upload/upload'
import UploadZip from '@/components/upload/uploadZip'
import { EBbase } from '../EBbase.js'
import Cookies from 'js-cookie'
import config from '@/config'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro.replace('/api', '/')

export default {
  name: '',

  props: {
    // companyId: {
    //   type: String,
    //   default: ''
    // },
    // companyName: {
    //   type: String,
    //   default: ''
    // },
    // employeeId: {
    //   type: String,
    //   default: ''
    // },
    // isOnlyView: {
    //   type: Boolean,
    //   default: false
    // }
  },

  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },

    // 编辑
    hasEdit () {
      return this.actionArr.indexOf('Edit') > -1
    }
  },

  components: {
    Upload,
    UploadZip
  },

  data () {
    return {
      isOnlyView: true,
      employeeId: '',
      companyId: '',
      // 附件form
      formEnclosure: {
        fujian: '',
        // laodonghetong: '',
        // yuangongshouce: '',
        // ruzhidangan: '',
        // peixunqiandao: '',
        // qitaziliao: '',
        yuangongzhaopian: ''
        // lizhizhengming: ''
      },
      formEnclosureItem: [
        { type: 'file', label: '附件', placeholder: '请上传附件', prop: 'fujian', model: 'fujian', style: 'ivu-col-span-24', files: [], fn: 'deleteEmpAtta', isShow: true },
        // {type: 'file', label: '劳动合同', placeholder: '请上传劳动合同', prop: 'laodonghetong', model: 'laodonghetong', style: 'ivu-col-span-24', files: [], fn: 'deleteEmpAtta', isShow: false},
        // {type: 'file', label: '员工手册', placeholder: '请上传员工手册', prop: 'yuangongshouce', model: 'yuangongshouce', style: 'ivu-col-span-24', files: [], fn: 'deleteEmpAtta', isShow: true},
        // {type: 'file', label: '入职档案', placeholder: '请上传入职档案', prop: 'ruzhidangan', model: 'ruzhidangan', style: 'ivu-col-span-24', files: [], fn: 'deleteEmpAtta', isShow: true},
        // {type: 'file', label: '培训签到表', placeholder: '请上传培训签到表', prop: 'peixunqiandao', model: 'peixunqiandao', style: 'ivu-col-span-24', files: [], fn: 'deleteEmpAtta', isShow: true},
        // {type: 'file', label: '其他资料', placeholder: '请上传其他资料', prop: 'qitaziliao', model: 'qitaziliao', style: 'ivu-col-span-24', files: [], fn: 'deleteEmpAtta', isShow: true},
        { type: 'file', label: '员工照片', placeholder: '请上传员工照片', prop: 'yuangongzhaopian', model: 'yuangongzhaopian', style: 'ivu-col-span-24', files: [], fn: 'deleteEmpPic', uploadType: 'zip', isShow: true }
        // {type: 'file', label: '离职证明', placeholder: '请上传离职证明', prop: 'lizhizhengming', model: 'lizhizhengming', style: 'ivu-col-span-24', files: [], fn: 'deleteEmpAtta', isShow: true},
      ],
      rules: {
        // yuangongzhaopian: [
        //   { required: true, message: '请上传员工照片' }
        // ],
      },
      params: {
        ID: '',
        rowVersion: '',
        categoryname: '',
        Atta: ''
      },
      isNext: false,
      // uploadUrl: '/Employee/Upload'
      downLoadUrl: '',
      isPreviewImgModal: false,
      currentPreviewImg: null,
      isFromRoster: null,
      isFromWaitInduction: null
    }
  },

  watch: {
  },

  mounted () {
    // this.uploadUrl = '/Employee/' + this.employeeId + '/Upload'
    this.employeeId = this.$route.query.employeeId // 员工ID
    this.companyId = this.$route.query.companyId // 公司ID
    this.companyName = this.$route.query.companyName // 公司名称
    this.isFromRoster = this.$route.query.isFromRoster // 是否从员工管理页面过来
    this.isFromWaitInduction = this.$route.query.isFromWaitInduction // 是否从待入职员工页面过来

    // URL参数有员工ID时，获取员工基本信息
    if (this.employeeId !== '' && this.employeeId !== undefined) {
      this.query()
      this.rules = {}
    }

    if (this.$route.query.isCreateNew) { // isCreateNew参数为true时，为新增
      this.isOnlyView = false
    }

    this.isNext = !this.$route.query.isCreateNew || this.$route.query.employeeId
    console.log('员工附件上传this.isNext: ', this.isNext)
  },

  methods: {
    // 监听所有调用的方法
    listenCall (methodsWords, ...values) {
      this[methodsWords](...values)
    },

    // 表单提交
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          // console.log('提交表单', this[name])
          this.isNext = true
          this.handlepageDown()
        } else {
          this.$Message.warning('请上传照片附件')
        }
      })
    },

    // 上一步
    handlepageUp () {
      Common.pageUp(this)
    },

    // 下一步
    handlepageDown () {
      Common.pageDown(this)
    },

    // 新建标签
    handleAddTag (index, model) {
      var num = this.formEnclosureItem[index].files.length
      this.formEnclosureItem[index].files.push(num)
      this.formEnclosure[model] = this.formEnclosureItem[index].files.join(',')
    },

    // 删除员工附件
    async deleteEmpAtta (index, c_index, id) {
      console.log('删除员工附件id: ', id)
      let res = await EmployeesApi.deleteEmpAtta({ attaid: id })
      console.log('删除员工附件: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.formEnclosureItem[index].files.splice(c_index, 1) // 本地数组删除
        // 把附件数组中的ID传入到formEnclosure.attaId里去，并转成字符串
        var tempArr = []
        this.formEnclosureItem[index].files.map(item => {
          tempArr.push(item.id)
        })
        this.formEnclosure.attaId = tempArr.join(',')

        console.log('this.formEnclosureItem[index].files.length： ', this.formEnclosureItem[index].files.length)
        if (this.formEnclosureItem[index].model === 'yuangongzhaopian' && this.formEnclosureItem[index].files.length === 0) {
          this.isNext = false
        }
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 删除员工照片附件
    async deleteEmpPic (index, c_index, id) {
      console.log('删除员工照片附件id: ', id)
      let res = await EmployeesApi.deleteEmpPic({ picattaid: id })
      console.log('删除员工照片附件: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.formEnclosureItem[index].files.splice(c_index, 1) // 本地数组删除
        // 把附件数组中的ID传入到formEnclosure.attaId里去，并转成字符串
        var tempArr = []
        this.formEnclosureItem[index].files.map(item => {
          tempArr.push(item.id)
        })
        this.formEnclosure.attaId = tempArr.join(',')

        console.log('this.formEnclosureItem[index].files.length： ', this.formEnclosureItem[index].files.length)
        if (this.formEnclosureItem[index].model === 'yuangongzhaopian' && this.formEnclosureItem[index].files.length === 0) {
          this.isNext = false
        }
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    handleBeforeUpload (row) {
      console.log('model: ' + this.formEnclosureItem[row].model)
      this.params.categoryname = this.formEnclosureItem[row].model
    },

    // 上传普通资料
    handleUploadSuccess (res, row) {
      console.log('上传普通资料')
      var files = this.formEnclosureItem[row].files
      var modelName = this.formEnclosureItem[row].model
      if (res.code === 200 && res.success) {
        // this.$Message.success(res.message)
        var tempObj = {
          associationId: res.data.id,
          downLoadUrl: baseUrl + 'api/Employee/DownloadFile?id=' + res.data.id
        }
        files.push({ ...res.data, ...tempObj })
        console.log('res: ', res)
        console.log('files: ', files)
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
      var tempArr = []
      files.map(item => {
        tempArr.push(item.id)
      })
      this.formEnclosure[modelName] = tempArr.join(',')

      if (this.formEnclosureItem[row].model === 'yuangongzhaopian' && this.formEnclosureItem[row].files.length > 0) {
        this.isNext = true
      }
    },

    // 上传员工照片
    handleUploadSuccessZip (res, row) {
      console.log('上传ZIP')
      var files = this.formEnclosureItem[row].files
      var modelName = this.formEnclosureItem[row].model
      if (res.code === 200 && res.success) {
        // this.$Message.success(res.message)
        files.push(res.data)
        console.log('res: ', res)
        console.log('files: ', files)
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
      var tempArr = []
      files.map(item => {
        tempArr.push(item.id)
      })
      this.formEnclosure[modelName] = tempArr.join(',')

      if (this.formEnclosureItem[row].model === 'yuangongzhaopian' && this.formEnclosureItem[row].files.length > 0) {
        this.isNext = true
      }
    },

    // 获取单个员工附件信息
    async query () {
      var self = this
      var params = {
        id: this.employeeId
      }
      let res = await EmployeesApi.getAttachmentList(params)
      if (res.data.code === 200 && res.data.success) {
        var result = res.data.data
        console.log('员工附件result: ', result)

        // 根据获取到的数据字段循环结果并赋值到表单
        result.map(item => {
          this.formEnclosure[item.categoryName] = item.name
          item.downLoadUrl = '/api/Employee/DownloadFile?id=' + item.associationId
          item.houzhui = (item.name + '').substring((item.name + '').lastIndexOf('.') + 1)
          console.log('item.houzhui: ', item.houzhui)

          switch (item.categoryName) {
            case 'fujian':
              this.formEnclosureItem[0].files.push(item)
              break
            case '身份证正面':
              this.formEnclosureItem[1].files.push(item)
              item.downLoadUrl = item.downLoadUrl
              item.isIdCard = true
              if (this.formEnclosureItem[1].files.length > 0) {
                this.isNext = true
              }
              break
            case '身份证背面':
              this.formEnclosureItem[1].files.push(item)
              item.isIdCard = true
              item.downLoadUrl = item.downLoadUrl
              if (this.formEnclosureItem[1].files.length > 0) {
                this.isNext = true
              }
              break
            // case 'laodonghetong':
            //   this.formEnclosureItem[0].files.push(item)
            //   break;
            // case 'yuangongshouce':
            //   this.formEnclosureItem[1].files.push(item)
            //   break;
            // case 'ruzhidangan':
            //   this.formEnclosureItem[2].files.push(item)
            //   break;
            // case 'peixunqiandao':
            //   this.formEnclosureItem[3].files.push(item)
            //   break;
            // case 'qitaziliao':
            //   this.formEnclosureItem[4].files.push(item)
            //   break;
            case 'yuangongzhaopian':
              this.formEnclosureItem[1].files.push(item)
              item.downLoadUrl = '/api/Employee/DownloadPictureFile?ids=' + this.employeeId
              if (this.formEnclosureItem[1].files.length > 0) {
                this.isNext = true
              }
              break
            // case 'lizhizhengming':
            //   this.formEnclosureItem[6].files.push(item)
            //   break;
          }
        })
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 修改
    handleModify () {
      // this.$emit('handleModify', 1)
      this.isOnlyView = false
    },

    // 压缩包下载
    async batchPictureUpload () {
      console.log('压缩包下载')
      let res = await EmployeesApi.downloadPictureFile([this.employeeId])
      if (res.status === 200 && res.data.success) {
        // this.$Message.success(res.data.message)
        console.log('❤ 返回链接: ', baseUrl + res.data.message)
        window.open(baseUrl + res.data.message, '_blank')
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 普通附件下载
    accessoryDownload (url) {
      console.log('普通附件下载 url: ', url)
      let token = Cookies.get('clientToken')
      console.log('下载url: ', baseUrl + url.replace('/api', 'api'))
      window.open(baseUrl + url.replace('/api', 'api'), '_blank')
    },

    downLoad(url,name){
      console.log('11111111111111111111111111111111111 url: ', url.replace('/api', 'api'))
      var xhr = new XMLHttpRequest();
      xhr.open('get', baseUrl + url.replace('/api', 'api'), true);
      xhr.responseType = "blob"; // 返回类型blob  blob 存储着大量的二进制数据
      xhr.setRequestHeader("Authorization", 'Bearer '+Cookies.get('clientToken'));
      xhr.onload = function () {
          console.log(xhr)
          if (this.status === 200) {
              var blob = this.response;
              var reader = new FileReader();
              reader.readAsDataURL(blob); // 转换为base64，可以直接放入a标签href
              reader.onload = function (e) {
                const link = document.createElement('a')
                link.download = name
                link.href = e.target.result;
                link.click()
              };
          }
      }
      xhr.send(); // 发送ajax请求
    },

    // 图片预览
    previewImg (url) {
      console.log(url)
      this.isPreviewImgModal = true
      this.currentPreviewImg = baseUrl + url.replace('/api', '')
    },

    // 返回员工花名册列表
    goEmployeeBookList () {
      EBbase.goEmployeeBookList(this.$router, this.companyId, this.companyName)
    },

    // 返回员工管理
    goRoster () {
      EBbase.goRoster(this.$router)
    }
  }
}
</script>

<style lang="less" scope>

</style>
